package com.example.jimuyutabletcontrol;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.baidu.mapapi.CoordType;
import com.baidu.mapapi.SDKInitializer;
import com.example.jimuyutabletcontrol.app.ActivityManage;
import com.example.jimuyutabletcontrol.app.ActivityManageImpl;
import com.example.jimuyutabletcontrol.heartbeatModule.Heartbeat;
import com.example.jimuyutabletcontrol.location.LocationProvider;
import com.example.jimuyutabletcontrol.network.udp.UdpMessageHandle;
import com.example.jimuyutabletcontrol.network.udp.UdpMessageType;
import com.example.jimuyutabletcontrol.network.udp.UdpSocket;
import com.example.jimuyutabletcontrol.port.TaskFileNameCallback;
import com.example.jimuyutabletcontrol.utils.IMEIUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.bugly.crashreport.CrashReport;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.annotation.NonNull;

public class MapApplication extends Application implements Application.ActivityLifecycleCallbacks {

    private static Context mContext;

    private static ActivityManage mActivityManage;

    public static int startCount = 0;

    private static boolean isCurrentProcess = false;

    private UdpMessageHandle taskListHandle;

    private static Map<String, List<String>> taskFiles;

    private static List<TaskFileNameCallback> fileNameCallbacks;

    @Override
    public void onCreate() {
        super.onCreate();
        String processName = getProcessName(this);
        isCurrentProcess = null != processName && processName.equals(getPackageName());
        if (isCurrentProcess) {
            CrashReport.initCrashReport(getApplicationContext(), "15d3515df7", false);//第三个参数为调试模式开关，开发调试时可为true
            mContext = getApplicationContext();
            mActivityManage = new ActivityManageImpl();
            registerActivityLifecycleCallbacks(this);
            UdpSocket.getInstance().init();
            startHeartbeat();
            SDKInitializer.initialize(this);
            SDKInitializer.setCoordType(CoordType.BD09LL);
            taskFiles = new HashMap<>();
            fileNameCallbacks = new ArrayList<>();
            setListeners();
        }
    }


    //////////////////////////////////////文件操作/////////////////////////////////////////////////
    //////////////////////////////////////////////////////////////////////////////////////////////

    public static void setFileTaskCallback(TaskFileNameCallback callback) {
        if (null == callback) return;
        if (fileNameCallbacks.contains(callback)) return;
        fileNameCallbacks.add(callback);
    }

    public static void removeFileTaskCallback(TaskFileNameCallback callback) {
        if (null == callback) return;
        if (!fileNameCallbacks.contains(callback)) return;
        fileNameCallbacks.remove(callback);
    }

    public static void refreshFileDataWithImei(String imei, boolean forceRefresh) {
        List<String> fileNames = taskFiles.get(imei);
        if (fileNames == null || fileNames.size() == 0 || forceRefresh) {
            UdpSocket.getInstance().sendMessage("B" + imei + "getTaskList");
        } else {
            if (null != fileNameCallbacks && fileNameCallbacks.size() > 0) {
                for (TaskFileNameCallback callback : fileNameCallbacks) {
                    callback.onTaskFileNameCallback(taskFiles);
                }
            }
        }
    }

    @SuppressLint("HandlerLeak")
    private void setListeners() {
        taskListHandle = new UdpMessageHandle(UdpMessageType.TASK_LIST, this::refreshTaskListData);
        UdpSocket.getInstance().setMessageCallback(taskListHandle);
    }

    private void refreshTaskListData(String s) {
        if (TextUtils.isEmpty(s)) return;
        String[] strs = s.split(",taskFileList_with-_-");
        String imei = strs[0];
        String json = strs[1];
        if (taskFiles.containsKey(imei)) {
            List<String> list = taskFiles.get(imei);
            if (null == list) {
                taskFiles.put(imei, list);
            }
        } else {
            taskFiles.put(imei, new ArrayList<>());
        }
        if (TextUtils.isEmpty(json)) return;
        if (json.equals("noExist")) return;
        List<String> list = new Gson().fromJson(json, new TypeToken<List<String>>() {
        }.getType());
        if (null == list) return;
        List<String> fileNames = taskFiles.get(imei);
        assert fileNames != null;
        fileNames.clear();
        fileNames.addAll(list);
        if (null != fileNameCallbacks && fileNameCallbacks.size() > 0) {
            for (TaskFileNameCallback callback : fileNameCallbacks) {
                callback.onTaskFileNameCallback(taskFiles);
            }
        }
    }

    public static List<String> getTaskFileDataWithImei(String imei) {
        return taskFiles.get(imei);
    }

    /////////////////////////////////////////////////////////////////////////////////////////////////



    private void startHeartbeat() {
        if (isCurrentProcess) {
            Heartbeat heartbeat = Heartbeat.getInstance();
            heartbeat.setHeartbeatTime(6 * 1000);
            heartbeat.registerCallback(() -> UdpSocket.getInstance().sendMessage("D0" + IMEIUtils.getIMEI()));
            Heartbeat.getInstance().startHeartbeat();
        }
    }

    /**
     * 获取context
     *
     * @return
     */
    public static Context getContext() {
        return mContext;
    }

    /**
     * 获取ActivityManage
     *
     * @return
     */
    public synchronized static ActivityManage getActivityManage() {
        if (isCurrentProcess) {
            if (mActivityManage == null) {
                mActivityManage = new ActivityManageImpl();
            }
        }
        return mActivityManage;
    }

    /**
     * 获取当前Activity
     *
     * @return
     */
    public synchronized static Activity getCurrentActivity() {
        if (isCurrentProcess) {
            if (mActivityManage == null) {
                mActivityManage = new ActivityManageImpl();
                return null;
            } else {
                if (mActivityManage.mActivitys.size() == 0) {
                    return null;
                } else {
                    return mActivityManage.currentActivity();
                }
            }
        } else return null;
    }

    /**
     * 获取指定activity对象
     *
     * @param cls
     * @return
     */
    public synchronized static Activity findActivity(Class<?> cls) {
        if (isCurrentProcess) {
            if (mActivityManage == null) {
                mActivityManage = new ActivityManageImpl();
                return null;
            } else {
                if (mActivityManage.mActivitys.size() == 0) {
                    return null;
                } else {
                    return mActivityManage.findActivity(cls);
                }
            }
        } else return null;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        startCount++;
        if (null == mActivityManage) {
            mActivityManage = new ActivityManageImpl();
        }
        mActivityManage.pushActivity(activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        startCount--;
        if (startCount <= 0) {
//            UdpSocket.getInstance().release();
//            Heartbeat.getInstance().stopHeartbeat();
//            UdpSocket.getInstance().removeMessageCallback(taskListHandle);
//            taskListHandle = null;
//            LocationProvider.getInstance().stopLocation();
//            if (null != fileNameCallbacks&&fileNameCallbacks.size()>0){
//                fileNameCallbacks.clear();
//                fileNameCallbacks = null;
//            }
        }
        if (mActivityManage == null) return;
        mActivityManage.popActivity(activity);
    }

    private String getProcessName(MapApplication mapApplication) {
        ActivityManager am = (ActivityManager) mapApplication.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                if (proInfo.processName != null) {
                    return proInfo.processName;
                }
            }
        }
        return null;
    }
}
